import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import {
  GitBranch,
  AlertTriangle,
  Info,
  Calculator,
  CheckCircle,
  Save,
  RefreshCw,
  Shield,
  X,
} from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import { isEqual } from "lodash";

export default function RulingSpanCalculator({
  scheme,
  onUpdate,
  crossingPoint,
  conductorSpecs,
}) {


  console.log(scheme,'schemescheme');
  console.log(crossingPoint,'crossingPointcrossingPoint');
  
  
  const { toast } = useToast();
  const [spanLengthsInput, setSpanLengthsInput] = useState("");
  const [parseError, setParseError] = useState("");

  const [baseParams, setBaseParams] = useState({
    calculationTemperatureNormal: 15,
    calculationTemperatureMax: 70,
    calculationTemperatureIce: -5,
    windPressureAtIce: 0.125,
    iceThicknessMm: 10,
    conductorSafetyFactorMin: 2.5,
  });

  const [calculationResults, setCalculationResults] = useState(null);
  const [calculationError, setCalculationError] = useState("");
  const [safetyCheckResults, setSafetyCheckResults] = useState(null);

  const currentConductorSpec = useMemo(() => {
    if (scheme.conductorType && Array.isArray(conductorSpecs)) {
      return conductorSpecs.find((spec) => spec.model === scheme.conductorType);
    }
    return null;
  }, [scheme.conductorType, conductorSpecs]);

  const conductorBreakingForce = useMemo(() => {
    if (scheme.conductorBreakingForce && scheme.conductorBreakingForce > 0) {
      return scheme.conductorBreakingForce;
    }

    if (currentConductorSpec && currentConductorSpec.breakingForceKN) {
      return currentConductorSpec.breakingForceKN;
    }

    return 0;
  }, [scheme.conductorBreakingForce, currentConductorSpec]);

  const calculatedConductorWeight = useMemo(() => {
    if (scheme.conductorWeightPerMeter && scheme.conductorWeightPerMeter > 0) {
      return scheme.conductorWeightPerMeter;
    }

    if (currentConductorSpec && currentConductorSpec.weightPerMeterNPerM) {
      return currentConductorSpec.weightPerMeterNPerM;
    }

    if (scheme.conductorUnitLoad && scheme.conductorCrossSectionalArea) {
      const unitLoad = parseFloat(scheme.conductorUnitLoad);
      const crossSectionalArea = parseFloat(scheme.conductorCrossSectionalArea);
      if (!isNaN(unitLoad) && !isNaN(crossSectionalArea)) {
        return unitLoad * crossSectionalArea;
      }
    }

    return 0;
  }, [
    scheme.conductorWeightPerMeter,
    scheme.conductorUnitLoad,
    scheme.conductorCrossSectionalArea,
    currentConductorSpec,
  ]);

  useEffect(() => {
    const schemeSpans = scheme.allSpanLengthsInTensionSection || [];
    let currentInputSpans = [];
    try {
      currentInputSpans = parseSpanLengths(spanLengthsInput);
    } catch (e) {
      // Ignore parse errors
    }

    if (!isEqual(schemeSpans, currentInputSpans)) {
      if (schemeSpans.length > 0) {
        setSpanLengthsInput(schemeSpans.join(", "));
      } else if (crossingPoint?.spanLength && !spanLengthsInput) {
        setSpanLengthsInput(crossingPoint.spanLength.toString());
      } else if (!schemeSpans.length && !spanLengthsInput) {
        setSpanLengthsInput("");
      }
    }
  }, [
    scheme.allSpanLengthsInTensionSection,
    crossingPoint?.id,
    crossingPoint?.spanLength,
    spanLengthsInput,
  ]);

  useEffect(() => {
    if (scheme.conductorBaseParametersAtRulingSpan) {
      const existing = scheme.conductorBaseParametersAtRulingSpan;
      setBaseParams((prev) => ({
        ...prev,
        calculationTemperatureNormal:
          existing.calculationTemperatureNormal ??
          prev.calculationTemperatureNormal,
        calculationTemperatureMax:
          existing.calculationTemperatureMax ?? prev.calculationTemperatureMax,
        calculationTemperatureIce:
          existing.calculationTemperatureIce ?? prev.calculationTemperatureIce,
        windPressureAtIce: existing.windPressureAtIce ?? prev.windPressureAtIce,
        iceThicknessMm: existing.iceThicknessMm ?? prev.iceThicknessMm,
        conductorSafetyFactorMin:
          existing.conductorSafetyFactorMin ?? prev.conductorSafetyFactorMin,
      }));
    }
  }, [scheme.conductorBaseParametersAtRulingSpan]);

  const parseSpanLengths = (input) => {
    if (!input || input.trim() === "") {
      return []; // 空输入返回空数组，由调用处判断
    }

    try {
      const spans = input
        .split(",")
        .map((s) => s.trim())
        .filter((s) => s !== "") // 过滤空字符串（如多逗号导致的空值）
        .map((s) => {
          const num = parseFloat(s);
          if (isNaN(num)) {
            throw new Error(`无效的数字格式: "${s}"`); // 明确是格式错误
          }
          if (num <= 0) {
            throw new Error(`档距必须为正数: "${s}"`); // 明确是数值错误
          }
          return num;
        });

      if (spans.length === 0) {
        throw new Error("输入为空或仅包含无效字符，请输入至少一个有效档距");
      }

      return spans;
    } catch (error) {
      throw error; // 向上传递错误，由调用处展示
    }
  };

  const calculateRulingSpan = (spanLengths) => {
    if (!spanLengths || spanLengths.length === 0) {
      return 0; // 空数组返回0，避免后续计算错误
    }

    const sumOfCubes = spanLengths.reduce(
      (sum, length) => sum + Math.pow(length, 3),
      0
    );
    const sumOfLengths = spanLengths.reduce((sum, length) => sum + length, 0);

    if (sumOfLengths === 0 || sumOfCubes === 0) {
      return 0; // 避免 0/0 导致的 NaN
    }

    return Math.sqrt(sumOfCubes / sumOfLengths);
  };

  const handleSpanLengthsChange = (value) => {
    setSpanLengthsInput(value);
    setParseError("");

    try {
      const spanLengths = parseSpanLengths(value);
      if (spanLengths.length === 0) {
        // 额外检查空数组
        throw new Error("请至少输入一个有效档距");
      }
      const rulingSpan = calculateRulingSpan(spanLengths);
      onUpdate({
        ...scheme,
        allSpanLengthsInTensionSection: spanLengths,
        rulingSpanCalculated: rulingSpan,
      });
    } catch (error) {
      setParseError(error.message || "档距解析失败，请检查输入格式");
      onUpdate({
        ...scheme,
        allSpanLengthsInTensionSection: [],
        rulingSpanCalculated: 0,
      });
    }
  };

  const handleTensionSectionToggle = (enabled) => {
    const updatedScheme = {
      ...scheme,
      isTensionSectionCrossing: enabled,
      allSpanLengthsInTensionSection: enabled
        ? scheme.allSpanLengthsInTensionSection || []
        : [],
      rulingSpanCalculated: enabled ? scheme.rulingSpanCalculated || 0 : 0,
    };

    if (!enabled) {
      setSpanLengthsInput("");
      setParseError("");
      setCalculationResults(null);
      setCalculationError("");
      setSafetyCheckResults(null);
    } else if (!spanLengthsInput && crossingPoint?.spanLength) {
      setSpanLengthsInput(crossingPoint.spanLength.toString());
      handleSpanLengthsChange(crossingPoint.spanLength.toString());
    }

    onUpdate(updatedScheme);
  };

  const handleAutoFillConductorWeight = useCallback(() => {
    const weight = calculatedConductorWeight;
    if (weight > 0) {
      onUpdate({
        ...scheme,
        conductorWeightPerMeter: weight,
      });

      toast({
        title: "数据已补充",
        description: `导线单位重量已自动设置为 ${weight.toFixed(2)} N/m`,
      });
    } else {
      toast({
        variant: "destructive",
        title: "无法自动补充",
        description:
          "请检查导线规格数据是否完整，或在基本信息中手动设置导线参数。",
      });
    }
  }, [calculatedConductorWeight, scheme, onUpdate, toast]);

  const performSafetyCheck = useCallback(
    (results, breakingForce, crossSectionalArea, minSafetyFactor) => {
      if (
        !results ||
        !breakingForce ||
        breakingForce <= 0 ||
        !crossSectionalArea ||
        crossSectionalArea <= 0
      ) {
        return null;
      }

      const breakingForceN = breakingForce * 1000;
      const crossSectionalAreaM2 = crossSectionalArea * 1e-6;

      const checkWorkCondition = (conditionName, HKN) => {
        if (!HKN || HKN <= 0) return null;

        const HN = HKN * 1000;
        const actualStress = HN / crossSectionalAreaM2;
        const currentSafetyFactor = breakingForceN / HN;
        const isPass = currentSafetyFactor >= minSafetyFactor;

        return {
          condition: conditionName,
          horizontalTensionKN: HKN,
          actualStressMPa: actualStress / 1e6,
          currentSafetyFactor: currentSafetyFactor,
          minSafetyFactor: minSafetyFactor,
          isPass: isPass,
        };
      };

      const normalCheck = checkWorkCondition(
        "正常运行",
        results.normalOperation?.horizontalTensionH / 1000
      );
      const maxTempCheck = checkWorkCondition(
        "最高温度",
        results.maxTemperature?.horizontalTensionH / 1000
      );
      const iceWindCheck = checkWorkCondition(
        "覆冰+风",
        results.iceWind?.horizontalTensionH / 1000
      );

      const allChecks = [normalCheck, maxTempCheck, iceWindCheck].filter(
        Boolean
      );
      const overallPass =
        allChecks.length > 0 && allChecks.every((check) => check.isPass);

      return {
        normal: normalCheck,
        maxTemp: maxTempCheck,
        iceWind: iceWindCheck,
        overallPass: overallPass,
        allChecks: allChecks,
      };
    },
    []
  );

  const calculateConductorBaseParameters = () => {
    setCalculationError("");
    setSafetyCheckResults(null);

    try {
      const rulingSpan = scheme.rulingSpanCalculated;
      if (!rulingSpan || rulingSpan <= 0) {
        throw new Error("请先输入档距并计算出有效的代表档距");
      }

      const conductorWeight = calculatedConductorWeight;
      if (!conductorWeight || conductorWeight <= 0) {
        throw new Error(
          '导线单位重量数据缺失。请点击"自动补充"按钮或在基本信息中完善导线规格。'
        );
      }

      const elasticModulus =
        scheme.conductorElasticModulus ||
        currentConductorSpec?.elasticModulusMPa;
      const thermalExpansionCoeff =
        scheme.conductorThermalExpansionCoeff ||
        currentConductorSpec?.thermalExpansionCoeffPerC ||
        2.3e-5;
      const designOperatingStress =
        scheme.conductorDesignOperatingStress ||
        currentConductorSpec?.designOperatingStressMPa;
      const crossSectionalArea =
        scheme.conductorCrossSectionalArea ||
        currentConductorSpec?.crossSectionalAreaMm2;

      if (!elasticModulus || elasticModulus <= 0) {
        throw new Error("导线弹性模量数据缺失，请在基本信息中完善导线规格");
      }
      if (!designOperatingStress || designOperatingStress <= 0) {
        throw new Error("导线设计运行应力数据缺失，请在基本信息中完善导线规格");
      }
      if (!crossSectionalArea || crossSectionalArea <= 0) {
        throw new Error("导线截面积数据缺失，请在基本信息中完善导线规格");
      }

      const g = 9.8;
      const q0 = conductorWeight;
      const E = elasticModulus * 1e6;
      const α = thermalExpansionCoeff;
      const σ0 = designOperatingStress * 1e6;
      const A = crossSectionalArea * 1e-6;
      const w0 =
        scheme.designWindPressureStandardValue ||
        crossingPoint?.designWindPressureStandardValue ||
        0.4;
      const μs = 1.2;

      const results = {};

      const TNormal = baseParams.calculationTemperatureNormal;
      const q1 = q0;
      const H1 = σ0 * A;
      const f1 = (q1 * Math.pow(rulingSpan, 2)) / (8 * H1);

      results.normalOperation = {
        temperature: TNormal,
        loadPerMeter: q1,
        horizontalTensionH: H1,
        sag: f1,
        stress: H1 / A,
      };

      const TMax = baseParams.calculationTemperatureMax;
      const ΔTMax = TMax - TNormal;
      const q2 = q0;
      const thermalStressReduction = α * E * A * ΔTMax;
      const H2 = Math.max(H1 - thermalStressReduction, H1 * 0.3);
      const f2 = (q2 * Math.pow(rulingSpan, 2)) / (8 * H2);

      results.maxTemperature = {
        temperature: TMax,
        loadPerMeter: q2,
        horizontalTensionH: H2,
        sag: f2,
        stress: H2 / A,
      };

      const TIce = baseParams.calculationTemperatureIce;
      const tIce = baseParams.iceThicknessMm * 1e-3;
      const wIce = baseParams.windPressureAtIce * 1000;
      const conductorDiameter =
        scheme.conductorOuterDiameter ||
        currentConductorSpec?.outerDiameterMm ||
        30;
      const d = conductorDiameter * 1e-3;

      const dIce = d + 2 * tIce;
      const iceDensity = 900;
      const iceVolumePerMeter =
        Math.PI * ((Math.pow(dIce, 2) - Math.pow(d, 2)) / 4);
      const iceWeightPerMeter = iceVolumePerMeter * iceDensity * g;

      const q3Vertical = q0 + iceWeightPerMeter;
      const q3Wind = wIce * dIce;
      const q3Combined = Math.sqrt(
        Math.pow(q3Vertical, 2) + Math.pow(q3Wind, 2)
      );

      const ΔTIce = TIce - TNormal;
      const thermalTensionIncrease = -α * E * A * ΔTIce;
      const H3 = H1 + thermalTensionIncrease;
      const f3 = (q3Combined * Math.pow(rulingSpan, 2)) / (8 * H3);

      results.iceWind = {
        temperature: TIce,
        loadPerMeter: q3Combined,
        verticalLoad: q3Vertical,
        windLoad: q3Wind,
        horizontalTensionH: H3,
        sag: f3,
        stress: H3 / A,
        iceThickness: tIce * 1000,
        iceDiameter: dIce * 1000,
      };

      const safetyCheck = performSafetyCheck(
        results,
        conductorBreakingForce,
        crossSectionalArea,
        baseParams.conductorSafetyFactorMin
      );
      setSafetyCheckResults(safetyCheck);

      const baseParametersData = {
        normalOperationHKN: results.normalOperation.horizontalTensionH / 1000,
        normalOperationSagM: results.normalOperation.sag,
        maxTempHKN: results.maxTemperature.horizontalTensionH / 1000,
        maxTempSagM: results.maxTemperature.sag,
        iceWindHKN: results.iceWind.horizontalTensionH / 1000,
        iceWindSagM: results.iceWind.sag,
        calculationTemperatureNormal: baseParams.calculationTemperatureNormal,
        calculationTemperatureMax: baseParams.calculationTemperatureMax,
        calculationTemperatureIce: baseParams.calculationTemperatureIce,
        windPressureAtIce: baseParams.windPressureAtIce,
        iceThicknessMm: baseParams.iceThicknessMm,
        conductorSafetyFactorMin: baseParams.conductorSafetyFactorMin,
      };

      onUpdate({
        ...scheme,
        conductorWeightPerMeter: conductorWeight,
        conductorBaseParametersAtRulingSpan: baseParametersData,
      });

      setCalculationResults(results);

      const safetyStatus = safetyCheck?.overallPass
        ? "所有工况的安全系数均满足要求"
        : "部分工况的安全系数不满足要求，请检查";
      toast({
        title: "计算完成",
        description: `导线基准参数计算完成并已保存。${safetyStatus}`,
        variant: safetyCheck?.overallPass ? undefined : "destructive",
      });
    } catch (error) {
      console.error("导线基准参数计算失败:", error);
      setCalculationError(error.message);
      toast({
        variant: "destructive",
        title: "计算失败",
        description: error.message,
      });
    }
  };

  const spanLengths = scheme.allSpanLengthsInTensionSection || [];
  const rulingSpan = scheme.rulingSpanCalculated || 0;
  const localSpan = crossingPoint?.spanLength || 0;
  const baseParametersCalculated = scheme.conductorBaseParametersAtRulingSpan;

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <GitBranch className="w-5 h-5 text-blue-600" />
            基准参数计算（勘查单）
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <Alert variant="default" className="bg-yellow-50 border-yellow-200">
            <AlertTriangle className="h-4 w-4 !text-yellow-600" />
            <AlertTitle className="text-yellow-800">
              DL/T 5301-2013 标准要求
            </AlertTitle>
            <AlertDescription className="text-yellow-700">
              <div className="space-y-2 text-sm">
                <p>
                  <strong>局部跨越档用孤立档补充计算的两步法：</strong>
                </p>
                <p>
                  <strong>步骤1：</strong>
                  用代表档距计算勘查单全段基准参数（导线张力-弧垂状态）
                </p>
                <p>
                  <strong>步骤2：</strong>
                  用局部跨越档距补充校验与修正（特殊风险管控）
                </p>
                <p className="text-red-600 font-medium">
                  ⚠️
                  禁止用局部跨越档距替代代表档距，避免因计算逻辑错误引发安全事故
                </p>
              </div>
            </AlertDescription>
          </Alert>

          <div className="flex items-center justify-between">
            <Label
              htmlFor="tension-section-switch"
              className="text-base font-medium"
            >
              启用勘查单计算
            </Label>
            <Switch
              id="tension-section-switch"
              checked={scheme.isTensionSectionCrossing || false}
              onCheckedChange={handleTensionSectionToggle}
            />
          </div>

          <p className="text-sm text-gray-600">
            当跨越点位于长勘查单内（两个耐张塔之间有直线塔）时，需要启用此功能以确保符合规范要求。
          </p>
        </CardContent>
      </Card>

      {scheme.isTensionSectionCrossing && (
        <>
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">勘查单档距配置</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="span-lengths-input">
                  勘查单内所有档距长度（米）
                </Label>
                <Input
                  id="span-lengths-input"
                  placeholder="例如: 250, 300, 280, 295"
                  value={spanLengthsInput}
                  onChange={(e) => handleSpanLengthsChange(e.target.value)}
                  className={parseError ? "border-red-500" : ""}
                />
                <p className="text-xs text-gray-500 mt-1">
                  请输入勘查单内所有档距的长度，用英文逗号分隔。包括跨越档和非跨越档。
                </p>
                {parseError && (
                  <p className="text-sm text-red-600 mt-1">{parseError}</p>
                )}
              </div>

              {spanLengths.length > 0 && !parseError && (
                <div className="space-y-3">
                  <div>
                    <Label className="text-sm font-medium">档距统计</Label>
                    <div className="flex flex-wrap gap-2 mt-1">
                      {spanLengths.map((span, index) => (
                        <Badge key={index} variant="outline">
                          第{index + 1}档: {span}m
                        </Badge>
                      ))}
                    </div>
                  </div>

                  <Separator />

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="text-center">
                      <div className="text-2xl font-bold text-blue-600">
                        {rulingSpan.toFixed(1)}
                      </div>
                      <div className="text-sm text-gray-600">代表档距 (m)</div>
                      <div className="text-xs text-gray-500 mt-1">
                        Lr = √(ΣLi³/ΣLi)
                      </div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-green-600">
                        {localSpan}
                      </div>
                      <div className="text-sm text-gray-600">
                        局部跨越档距 (m)
                      </div>
                      <div className="text-xs text-gray-500 mt-1">
                        用于局部校验
                      </div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-gray-600">
                        {spanLengths.length}
                      </div>
                      <div className="text-sm text-gray-600">档距总数</div>
                      <div className="text-xs text-gray-500 mt-1">勘查单内</div>
                    </div>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Calculator className="w-5 h-5 text-purple-600" />
                导线基准参数计算（步骤1）
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <Alert className="bg-blue-50 border-blue-200">
                <Info className="h-4 w-4 text-blue-600" />
                <AlertDescription className="text-blue-800 text-sm">
                  <strong>计算说明：</strong>
                  基于代表档距计算导线在各种工况下的水平张力H和弧垂，
                  这些基准参数将被承载索与净空校验模块引用，确保荷载计算的准确性。
                </AlertDescription>
              </Alert>

              <div className="p-3 border rounded-lg bg-gray-50">
                <h4
                  className="text-sm font-medium mb-3"
                  onClick={() => {
                    console.log(scheme, "schemescheme");
                  }}
                >
                  导线参数检查
                </h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-xs">
                  <div className="flex items-center justify-between p-2 bg-white rounded border">
                    <span>导线型号:</span>
                    <span
                      className={
                        crossingPoint.conductorType
                          ? "text-green-600 font-medium"
                          : "text-red-600"
                      }
                    >
                      {crossingPoint.conductorType || "未设置"}
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-2 bg-white rounded border">
                    <span>额定拉断力 (kN):</span>
                    <span
                      className={
                        conductorBreakingForce > 0
                          ? "text-green-600 font-medium"
                          : "text-red-600"
                      }
                    >
                      {conductorBreakingForce > 0
                        ? conductorBreakingForce.toFixed(1)
                        : "缺失"}
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-2 bg-white rounded border">
                    <span>单位重量 (N/m):</span>
                    <div className="flex items-center gap-2">
                      <span
                        className={
                          calculatedConductorWeight > 0
                            ? "text-green-600 font-medium"
                            : "text-red-600"
                        }
                      >
                        {calculatedConductorWeight > 0
                          ? calculatedConductorWeight.toFixed(2)
                          : "缺失"}
                      </span>
                      {calculatedConductorWeight > 0 &&
                        !scheme.conductorWeightPerMeter && (
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={handleAutoFillConductorWeight}
                            className="h-6 px-2 text-xs"
                          >
                            <RefreshCw className="w-3 h-3 mr-1" />
                            自动补充
                          </Button>
                        )}
                    </div>
                  </div>
                  <div className="flex items-center justify-between p-2 bg-white rounded border">
                    <span>弹性模量 (MPa):</span>
                    <span
                      className={
                        scheme.conductorElasticModulus ||
                        currentConductorSpec?.elasticModulusMPa
                          ? "text-green-600 font-medium"
                          : "text-red-600"
                      }
                    >
                      {scheme.conductorElasticModulus ||
                        currentConductorSpec?.elasticModulusMPa ||
                        "缺失"}
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-2 bg-white rounded border">
                    <span>设计运行应力 (MPa):</span>
                    <span
                      className={
                        scheme.conductorDesignOperatingStress ||
                        currentConductorSpec?.designOperatingStressMPa
                          ? "text-green-600 font-medium"
                          : "text-red-600"
                      }
                    >
                      {scheme.conductorDesignOperatingStress ||
                        currentConductorSpec?.designOperatingStressMPa ||
                        "缺失"}
                    </span>
                  </div>
                  <div className="flex items-center justify-between p-2 bg-white rounded border">
                    <span>截面积 (mm²):</span>
                    <span
                      className={
                        scheme.conductorCrossSectionalArea ||
                        currentConductorSpec?.crossSectionalAreaMm2
                          ? "text-green-600 font-medium"
                          : "text-red-600"
                      }
                    >
                      {scheme.conductorCrossSectionalArea ||
                        currentConductorSpec?.crossSectionalAreaMm2 ||
                        "缺失"}
                    </span>
                  </div>
                </div>

                {calculatedConductorWeight > 0 &&
                  !scheme.conductorWeightPerMeter && (
                    <Alert className="mt-3 bg-yellow-50 border-yellow-200">
                      <Info className="h-4 w-4 text-yellow-600" />
                      <AlertDescription className="text-yellow-800 text-xs">
                        <strong>提示：</strong>系统已计算出导线单位重量为{" "}
                        {calculatedConductorWeight.toFixed(2)} N/m，
                        请点击"自动补充"按钮将其保存到方案中，或在基本信息中手动设置。
                      </AlertDescription>
                    </Alert>
                  )}
              </div>

              <div className="grid grid-cols-2 md:grid-cols-3 gap-4 p-4 bg-gray-50 rounded-lg">
                <div>
                  <Label className="text-xs">正常运行温度 (°C)</Label>
                  <Input
                    type="number"
                    value={baseParams.calculationTemperatureNormal}
                    onChange={(e) =>
                      setBaseParams((prev) => ({
                        ...prev,
                        calculationTemperatureNormal:
                          parseFloat(e.target.value) || 15,
                      }))
                    }
                    className="h-8"
                  />
                </div>
                <div>
                  <Label className="text-xs">最高温度 (°C)</Label>
                  <Input
                    type="number"
                    value={baseParams.calculationTemperatureMax}
                    onChange={(e) =>
                      setBaseParams((prev) => ({
                        ...prev,
                        calculationTemperatureMax:
                          parseFloat(e.target.value) || 70,
                      }))
                    }
                    className="h-8"
                  />
                </div>
                <div>
                  <Label className="text-xs">覆冰温度 (°C)</Label>
                  <Input
                    type="number"
                    value={baseParams.calculationTemperatureIce}
                    onChange={(e) =>
                      setBaseParams((prev) => ({
                        ...prev,
                        calculationTemperatureIce:
                          parseFloat(e.target.value) || -5,
                      }))
                    }
                    className="h-8"
                  />
                </div>
                <div>
                  <Label className="text-xs">覆冰风压 (kN/m²)</Label>
                  <Input
                    type="number"
                    step="0.001"
                    value={baseParams.windPressureAtIce}
                    onChange={(e) =>
                      setBaseParams((prev) => ({
                        ...prev,
                        windPressureAtIce: parseFloat(e.target.value) || 0.125,
                      }))
                    }
                    className="h-8"
                  />
                </div>
                <div>
                  <Label className="text-xs">覆冰厚度 (mm)</Label>
                  <Input
                    type="number"
                    value={baseParams.iceThicknessMm}
                    onChange={(e) =>
                      setBaseParams((prev) => ({
                        ...prev,
                        iceThicknessMm: parseFloat(e.target.value) || 10,
                      }))
                    }
                    className="h-8"
                  />
                </div>
                <div>
                  <Label className="text-xs flex items-center gap-1">
                    <Shield className="w-3 h-3 text-blue-500" />
                    导线运行安全系数（最低要求）
                  </Label>
                  <Input
                    type="number"
                    step="0.1"
                    min="1.0"
                    value={baseParams.conductorSafetyFactorMin}
                    onChange={(e) => {
                      const value = parseFloat(e.target.value) || 2.5;
                      if (value >= 1.0) {
                        setBaseParams((prev) => ({
                          ...prev,
                          conductorSafetyFactorMin: value,
                        }));
                      }
                    }}
                    className="h-8"
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    用于校验各工况下导线强度安全性
                  </p>
                </div>
              </div>

              <div className="flex justify-center">
                <Button
                  onClick={calculateConductorBaseParameters}
                  disabled={
                    !rulingSpan ||
                    rulingSpan <= 0 ||
                    calculatedConductorWeight <= 0 ||
                    conductorBreakingForce <= 0
                  }
                  className="bg-purple-600 hover:bg-purple-700"
                >
                  <Calculator className="w-4 h-4 mr-2" />
                  计算导线基准参数
                </Button>
              </div>

              {calculationError && (
                <Alert variant="destructive">
                  <AlertTriangle className="h-4 w-4" />
                  <AlertDescription>{calculationError}</AlertDescription>
                </Alert>
              )}

              {safetyCheckResults && !safetyCheckResults.overallPass && (
                <Alert
                  variant="destructive"
                  className="bg-red-50 border-red-300"
                >
                  <X className="h-4 w-4 text-red-600" />
                  <AlertTitle className="text-red-800">
                    安全系数校验未通过
                  </AlertTitle>
                  <AlertDescription className="text-red-700">
                    部分工况下的导线安全系数不满足要求（小于{" "}
                    {baseParams.conductorSafetyFactorMin.toFixed(1)}）。
                    请考虑：1) 调整设计运行应力，2) 选用更高强度的导线，或 3)
                    重新评估安全系数要求。
                  </AlertDescription>
                </Alert>
              )}

              {baseParametersCalculated && (
                <div className="space-y-4">
                  <Separator />
                  <div>
                    <h4 className="font-medium text-lg mb-3 text-center">
                      导线基准参数计算结果
                    </h4>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <Card className="bg-green-50 border-green-200">
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm text-green-800">
                            正常运行工况
                          </CardTitle>
                        </CardHeader>
                        <CardContent className="text-xs space-y-2">
                          <div className="flex justify-between">
                            <span>水平张力 H:</span>
                            <span className="font-bold">
                              {baseParametersCalculated.normalOperationHKN.toFixed(
                                2
                              )}{" "}
                              kN
                            </span>
                          </div>
                          <div className="flex justify-between">
                            <span>弧垂:</span>
                            <span className="font-bold">
                              {baseParametersCalculated.normalOperationSagM.toFixed(
                                3
                              )}{" "}
                              m
                            </span>
                          </div>
                          <div className="flex justify-between">
                            <span>温度:</span>
                            <span>
                              {
                                baseParametersCalculated.calculationTemperatureNormal
                              }
                              °C
                            </span>
                          </div>
                          {safetyCheckResults?.normal && (
                            <>
                              <Separator />
                              <div className="flex justify-between items-center">
                                <span>安全系数:</span>
                                <div className="flex items-center gap-1">
                                  <span
                                    className={`font-bold ${
                                      safetyCheckResults.normal.isPass
                                        ? "text-green-600"
                                        : "text-red-600"
                                    }`}
                                  >
                                    {safetyCheckResults.normal.currentSafetyFactor.toFixed(
                                      2
                                    )}
                                  </span>
                                  {safetyCheckResults.normal.isPass ? (
                                    <CheckCircle className="w-3 h-3 text-green-600" />
                                  ) : (
                                    <X className="w-3 h-3 text-red-600" />
                                  )}
                                </div>
                              </div>
                              <div className="text-xs text-gray-600">
                                要求 ≥{" "}
                                {safetyCheckResults.normal.minSafetyFactor.toFixed(
                                  1
                                )}
                              </div>
                            </>
                          )}
                        </CardContent>
                      </Card>

                      <Card className="bg-orange-50 border-orange-200">
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm text-orange-800">
                            最高温工况
                          </CardTitle>
                        </CardHeader>
                        <CardContent className="text-xs space-y-2">
                          <div className="flex justify-between">
                            <span>水平张力 H:</span>
                            <span className="font-bold">
                              {baseParametersCalculated.maxTempHKN.toFixed(2)}{" "}
                              kN
                            </span>
                          </div>
                          <div className="flex justify-between">
                            <span>弧垂:</span>
                            <span className="font-bold">
                              {baseParametersCalculated.maxTempSagM.toFixed(3)}{" "}
                              m
                            </span>
                          </div>
                          <div className="flex justify-between">
                            <span>温度:</span>
                            <span>
                              {
                                baseParametersCalculated.calculationTemperatureMax
                              }
                              °C
                            </span>
                          </div>
                          {safetyCheckResults?.maxTemp && (
                            <>
                              <Separator />
                              <div className="flex justify-between items-center">
                                <span>安全系数:</span>
                                <div className="flex items-center gap-1">
                                  <span
                                    className={`font-bold ${
                                      safetyCheckResults.maxTemp.isPass
                                        ? "text-green-600"
                                        : "text-red-600"
                                    }`}
                                  >
                                    {safetyCheckResults.maxTemp.currentSafetyFactor.toFixed(
                                      2
                                    )}
                                  </span>
                                  {safetyCheckResults.maxTemp.isPass ? (
                                    <CheckCircle className="w-3 h-3 text-green-600" />
                                  ) : (
                                    <X className="w-3 h-3 text-red-600" />
                                  )}
                                </div>
                              </div>
                              <div className="text-xs text-gray-600">
                                要求 ≥{" "}
                                {safetyCheckResults.maxTemp.minSafetyFactor.toFixed(
                                  1
                                )}
                              </div>
                            </>
                          )}
                        </CardContent>
                      </Card>

                      <Card className="bg-blue-50 border-blue-200">
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm text-blue-800">
                            覆冰+风工况
                          </CardTitle>
                        </CardHeader>
                        <CardContent className="text-xs space-y-2">
                          <div className="flex justify-between">
                            <span>水平张力 H:</span>
                            <span className="font-bold">
                              {baseParametersCalculated.iceWindHKN.toFixed(2)}{" "}
                              kN
                            </span>
                          </div>
                          <div className="flex justify-between">
                            <span>弧垂:</span>
                            <span className="font-bold">
                              {baseParametersCalculated.iceWindSagM.toFixed(3)}{" "}
                              m
                            </span>
                          </div>
                          <div className="flex justify-between">
                            <span>温度:</span>
                            <span>
                              {
                                baseParametersCalculated.calculationTemperatureIce
                              }
                              °C
                            </span>
                          </div>
                          <div className="flex justify-between">
                            <span>覆冰厚度:</span>
                            <span>
                              {baseParametersCalculated.iceThicknessMm}mm
                            </span>
                          </div>
                          {safetyCheckResults?.iceWind && (
                            <>
                              <Separator />
                              <div className="flex justify-between items-center">
                                <span>安全系数:</span>
                                <div className="flex items-center gap-1">
                                  <span
                                    className={`font-bold ${
                                      safetyCheckResults.iceWind.isPass
                                        ? "text-green-600"
                                        : "text-red-600"
                                    }`}
                                  >
                                    {safetyCheckResults.iceWind.currentSafetyFactor.toFixed(
                                      2
                                    )}
                                  </span>
                                  {safetyCheckResults.iceWind.isPass ? (
                                    <CheckCircle className="w-3 h-3 text-green-600" />
                                  ) : (
                                    <X className="w-3 h-3 text-red-600" />
                                  )}
                                </div>
                              </div>
                              <div className="text-xs text-gray-600">
                                要求 ≥{" "}
                                {safetyCheckResults.iceWind.minSafetyFactor.toFixed(
                                  1
                                )}
                              </div>
                            </>
                          )}
                        </CardContent>
                      </Card>
                    </div>
                  </div>

                  <Alert
                    className={
                      safetyCheckResults?.overallPass
                        ? "bg-green-50 border-green-200"
                        : "bg-yellow-50 border-yellow-300"
                    }
                  >
                    {safetyCheckResults?.overallPass ? (
                      <CheckCircle className="h-4 w-4 text-green-600" />
                    ) : (
                      <AlertTriangle className="h-4 w-4 text-yellow-600" />
                    )}
                    <AlertDescription
                      className={
                        safetyCheckResults?.overallPass
                          ? "text-green-800"
                          : "text-yellow-800"
                      }
                    >
                      <strong>
                        {safetyCheckResults?.overallPass
                          ? "计算完成！"
                          : "计算完成但需注意！"}
                      </strong>
                      {safetyCheckResults?.overallPass ? (
                        <>
                          {" "}
                          导线基准参数已计算完成并保存，所有工况的安全系数均满足要求。现在可以前往&quot;承载索与净空校验&quot;标签页进行后续计算。
                        </>
                      ) : (
                        <>
                          {" "}
                          导线基准参数已计算完成并保存，但部分工况的安全系数不满足要求。建议在进行承载索计算前先调整相关参数。
                        </>
                      )}
                    </AlertDescription>
                  </Alert>
                </div>
              )}
            </CardContent>
          </Card>
        </>
      )}

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Info className="w-4 h-4" />
            使用说明
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3 text-sm">
            <div className="flex items-start gap-2">
              <CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
              <div>
                <strong>启用勘查单计算：</strong>
                当跨越点位于长勘查单内时，开启此开关。
              </div>
            </div>
            <div className="flex items-start gap-2">
              <CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
              <div>
                <strong>输入所有档距：</strong>
                包括跨越档和非跨越档的所有档距长度。
              </div>
            </div>
            <div className="flex items-start gap-2">
              <CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
              <div>
                <strong>检查导线参数：</strong>
                确保导线型号、单位重量、弹性模量、额定拉断力等参数完整。
              </div>
            </div>
            <div className="flex items-start gap-2">
              <Shield className="w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0" />
              <div>
                <strong>设置安全系数：</strong>
                根据项目标准要求设置导线运行安全系数（通常 ≥ 2.5）。
              </div>
            </div>
            <div className="flex items-start gap-2">
              <CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
              <div>
                <strong>计算基准参数：</strong>
                系统将基于代表档距计算导线在各工况下的基准张力和弧垂，并校验安全系数。
              </div>
            </div>
            <div className="flex items-start gap-2">
              <CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
              <div>
                <strong>进行承载索计算：</strong>
                前往&quot;承载索与净空校验&quot;标签页，系统将自动应用两步法。
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
